package com.pauldada.sakurabbs.security;

import com.pauldada.sakurabbs.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled " + "FROM user_account WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, role " + " FROM user_account WHERE username = ? ")
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().disable().headers().disable().authorizeRequests()
                .antMatchers("/tasks/new").hasRole("ADMIN")
                .antMatchers("/tasks/save").hasRole("ADMIN")
                .antMatchers("/members/new").hasRole("ADMIN")
                .antMatchers("/members/save").hasRole("ADMIN")
                .antMatchers("/comments/new").hasRole("ADMIN")
                .antMatchers("/comments/save").hasRole("ADMIN")
                .antMatchers("/admin","/**").hasRole("ADMIN")
                .antMatchers("/","/**").hasRole("ADMIN")
                .antMatchers("/userAccounts/info").hasRole("USER")
                .antMatchers("/","/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .successHandler(new LoginSuccessHandler());
//                .and()
//                .logout()
//                .permitAll();
    }
}